<?php

namespace app\api;

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Assets\Manager;

class Module implements ModuleDefinitionInterface
{
    /**
     * 注册
     * @param DiInterface|null $di
     */
    public function registerAutoloaders(DiInterface $di = null)
    {
        $loader = new Loader();

        $loader->registerNamespaces(
            [
                "app\\api\\controllers" => __DIR__.'/controllers/',
                "app\\api\\forms" => __DIR__.'/forms/',
            ]
        );

        $loader->register();
    }

    /**
     * 注册自定义服务
     */
    public function registerServices(DiInterface $di)
    {
        $di->setShared('url', function () {
            $config = include APP_PATH . "/config/config.php";

            $url = new UrlResolver();
            $url->setStaticBaseUri($config->application->baseUri);
            $url->setBaseUri($config->application->baseUri.'api/');
            return $url;
        });
        $di->set('assets',function(){
            $manager = new Manager();

            $manager->addCss('adminassets/css/bootstrap.min.css?v=3.3.5');
            $manager->addCss('adminassets/css/font-awesome.min.css?v=4.4.0');
            $manager->addCss('adminassets/css/animate.min.css');
            $manager->addCss('adminassets/css/style.min.css?v=4.0.0');

            $manager->addJs('adminassets/js/jquery.min.js');
            $manager->addJs('adminassets/js/bootstrap.min.js');

            return $manager;
        });
        // Registering the view component
        $di->set(
            "view",
            function () use($di){

                $view = new View();
                $view->setDI($di);
                $view->setViewsDir(__DIR__.'/views/');

                $view->registerEngines([
                    '.volt' =>function($view) use($di){
                        $config = include APP_PATH . "/config/config.php";

                        $volt = new VoltEngine($view, $di);

                        $volt->setOptions([
                            'compiledPath' => $config->application->cacheDir.'/api/',
                            'compiledSeparator' => '_'
                        ]);

                        return $volt;
                    }
                ]);

                return $view;
            }
        );
    }
}
